package com.ktjy.controller;

import com.ktjy.dto.LoginUser;
import com.ktjy.dto.WorkFlowDTO;
import com.ktjy.pojo.TbActivity;
import com.ktjy.service.WorkFlowService;
import com.ktjy.utils.AjaxResult;
import com.ktjy.utils.PageUtil;
import com.ktjy.vo.ActCommentEntity;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.IdentityLinkType;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/workFlow")
@Tag(name = "工作流活动申请")
@Slf4j
public class WorkFlowController {
    @Autowired
    WorkFlowService workFlowService;
    @Autowired
    private TaskService taskService;

    @Operation(summary = "启动工作流")
    @PutMapping("/startProcess/{id}")
    public AjaxResult startProcess(@PathVariable("id") Integer id) {
        try {
            workFlowService.startProcess("Activity2.0", id);
            return AjaxResult.success("启动工作流成功");
        } catch (Exception e) {
            log.error("WorkFlowController中startProcess方法执行报错的。", e);
        }
        return AjaxResult.error("启动工作流失败");
    }

    @Operation(summary = "查询当前登录用户的待办任务")
    @GetMapping("/loadTask")
    public AjaxResult loadTask(WorkFlowDTO workFlowDTO,
                               @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                               @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
        try {
            PageUtil page = workFlowService.findTask(workFlowDTO, pageNo, pageSize);
            return AjaxResult.success(page);
        } catch (Exception e) {
            log.error("WorkFlowController中loadTask方法执行报错的。", e);
        }
        return AjaxResult.error();
    }

    @Operation(summary = "根据任务ID查询业务数据")
    @GetMapping("/loadTask/{taskId}")
    public AjaxResult loadTask(@PathVariable("taskId") String taskId) {
        try {
            TbActivity activity = workFlowService.findActivityByTaskId(taskId);
            return AjaxResult.success(activity);
        } catch (Exception e) {
            log.error("WorkFlowController中loadTask方法执行报错的。", e);
        }
        return AjaxResult.error();
    }


    @Operation(summary = "根据任务ID查询批注信息")
    @GetMapping("/loadComment/{taskId}")
    public AjaxResult loadComment(@PathVariable("taskId") String taskId) {
        try {
            List<ActCommentEntity> comments = workFlowService.findCommentByTaskId(taskId);
            return AjaxResult.success(comments);
        } catch (Exception e) {
            log.error("WorkFlowController中loadComment方法执行报错的。", e);
        }
        return AjaxResult.error();
    }


    @Operation(summary = "驳回或完成任务")
    @PutMapping("/completeTask")
    public AjaxResult completeTask(@RequestBody WorkFlowDTO workFlowDTO) {
        try {
            workFlowService.completeTask(workFlowDTO);
            return AjaxResult.success("任务完成成功!");
        } catch (Exception e) {
            log.error("WorkFlowController中completeTask方法执行报错的。", e);
        }
        return AjaxResult.error("任务完成失败!");
    }

    @Operation(summary = "认领任务")
    @PostMapping("/claimTask/{taskId}")
    public synchronized AjaxResult claimTask(@PathVariable("taskId") String taskId) {
        try {
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();

            // 检查任务是否已经被认领
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task == null) {
                return AjaxResult.error("任务不存在");
            }

            if (task.getAssignee() != null && !task.getAssignee().isEmpty()) {
                return AjaxResult.error("任务已被 " + task.getAssignee() + " 认领，无法再次认领");
            }

            // 检查当前用户是否是候选用户
            List<IdentityLink> candidates = taskService.getIdentityLinksForTask(taskId); //获取候选用户
            boolean isCandidate = false;
            for (IdentityLink link : candidates) {
                if (IdentityLinkType.CANDIDATE.equals(link.getType()) &&
                        loginUser.getRealName().equals(link.getUserId())) {
                    isCandidate = true;
                    break;
                }
            }

            if (!isCandidate) {
                return AjaxResult.error("您不是该任务的候选办理人，无法认领此任务");
            }

            taskService.claim(taskId, loginUser.getRealName()); //认领任务设置认领人
            return AjaxResult.success("任务认领成功");
        } catch (Exception e) {
            log.error("认领任务失败", e);
            return AjaxResult.error("任务认领失败: " + e.getMessage());
        }
    }

    @Operation(summary = "取消认领任务")
    @PostMapping("/unclaimTask/{taskId}")
    public AjaxResult unclaimTask(@PathVariable("taskId") String taskId) {
        try {
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();

            // 检查任务是否存在且是当前用户认领的
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task == null) {
                return AjaxResult.error("任务不存在");
            }

            if (!loginUser.getRealName().equals(task.getAssignee())) {
                return AjaxResult.error("您不是该任务的办理人，无法取消认领");
            }

            taskService.unclaim(taskId);
            return AjaxResult.success("任务取消认领成功");
        } catch (Exception e) {
            log.error("取消认领任务失败", e);
            return AjaxResult.error("任务取消认领失败: " + e.getMessage());
        }
    }

}
